package com.gitee.ricesugar.mall.model.DAO;

import com.gitee.ricesugar.mall.model.POJO.DO.ProductDO;
import com.gitee.ricesugar.mall.model.POJO.DO.UserDO;
import com.gitee.ricesugar.mall.model.POJO.DTO.LoginDTO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UserDAO {

    Connection connection;

    public UserDAO() throws SQLException, ClassNotFoundException {
        connection = ConnectionPool.getInstance();
    }

    public UserDO login(String username, String password) throws SQLException {

        PreparedStatement statement = connection.prepareStatement("SELECT * FROM user WHERE username = ? AND password = ?");
        statement.setString(1, username);
        statement.setString(2, password);

        ResultSet resultSet = statement.executeQuery();

        UserDO userDO = null;

        if (resultSet.next()) {

            int id = resultSet.getInt("id");
            int uid = resultSet.getInt("uid");
            String uname = resultSet.getString("username");
            String pwd = resultSet.getString("password");

            userDO = new UserDO(id, uid, uname, pwd);
        }
        return userDO;
    }

    public UserDO register(String username, String password) throws SQLException {

        while (true) {
            int uid = java.util.UUID.randomUUID().toString().hashCode();

            // 检查是否重复
            PreparedStatement pStatement = connection.prepareStatement("SELECT * FROM user WHERE uid = ?");
            pStatement.setInt(1, uid);
            ResultSet resultSet = pStatement.executeQuery();
            if (!resultSet.next()) {
                PreparedStatement statement =
                        connection.prepareStatement("INSERT INTO user (uid, username, password) VALUES (?, ?, ?)");
                statement.setInt(1, uid);
                statement.setString(2, username);
                statement.setString(3, password);
                statement.executeUpdate();
                break;
            }
            resultSet.close();
            pStatement.close();
        }

        UserDO userDO = null;
        userDO = login(username, password);
        return userDO;
    }

    public boolean isUsernameExist(String username) throws SQLException {
        PreparedStatement pStatement = connection.prepareStatement("SELECT * FROM user WHERE username = ?");
        pStatement.setString(1, username);
        ResultSet resultSet = pStatement.executeQuery();
        return resultSet.next();
    }
}
